package com.agileai.miscdp.hotweb.ui.editors.mastersub;

import java.util.List;

import net.sf.swtaddons.autocomplete.combo.AutocompleteComboInput;

import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;

import com.agileai.miscdp.hotweb.database.DBManager;
import com.agileai.miscdp.hotweb.domain.mastersub.MasterSubFuncModel;
import com.agileai.miscdp.hotweb.domain.mastersub.SubTableConfig;
import com.agileai.miscdp.hotweb.ui.celleditors.SubTableConfigProviderEditor;
import com.agileai.miscdp.hotweb.ui.celleditors.TableViewerKeyboardSupporter;
import com.agileai.miscdp.hotweb.ui.editors.AddOrDelOperation;
import com.agileai.miscdp.hotweb.ui.editors.Modifier;
import com.agileai.miscdp.hotweb.ui.editors.UpOrDownOperation;
import com.agileai.miscdp.ui.TextCheckPolicy;
import com.agileai.miscdp.util.ResourceUtil;
import com.agileai.util.StringUtil;
/**
 * 基础配置页面
 */
public class MSBasicConfigPage extends Composite implements Modifier {
	private Table table;
	private MasterSubModelEditor modelEditor = null;
	private Text funcNameText;
	private Text funcTypeText;
	private final FormToolkit toolkit = new FormToolkit(Display.getCurrent());
	
	private MSExtendAttribute sMExtendAttribute;
	private Text listSqlText;
	private Combo tableNameCombo;

	private CellEditor[] subTableConfigEditors = null;
	private MasterSubFuncModel funcModel= null;
	private String[] tables = null;
	private Text funcSubPkgText;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private String[] getTables(){
		if (this.tables == null){
			String projectName = this.funcModel.getProjectName();
			List tableList = DBManager.getInstance(projectName).getTables(null);
			this.tables = (String[]) tableList.toArray(new String[0]);	
		}
		return this.tables;
	}
	/**
	 * Create the composite
	 * @param parent
	 * @param style
	 */
	public MSBasicConfigPage(Composite parent,MasterSubModelEditor modelEditor, int style) {
		super(parent, style);
		toolkit.adapt(this);
		toolkit.paintBordersFor(this);
		this.modelEditor = modelEditor;
		this.funcModel = modelEditor.getFuncModel();
//		createContent();
	}
	public void createContent(){
		final GridLayout gridLayout = new GridLayout();
		gridLayout.verticalSpacing = 2;
		gridLayout.marginWidth = 2;
		gridLayout.marginHeight = 2;
		gridLayout.horizontalSpacing = 2;
		gridLayout.numColumns = 3;
		setLayout(gridLayout);

		final Label label_1 = new Label(this, SWT.NONE);
		label_1.setText("功能名称");

		funcNameText = new Text(this, SWT.BORDER);
		toolkit.adapt(funcNameText, true, true);
		funcNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		new Label(this, SWT.NONE);

		final Label label = new Label(this, SWT.NONE);
		label.setText("功能类型");

		funcTypeText = new Text(this, SWT.READ_ONLY | SWT.BORDER);
		toolkit.adapt(funcTypeText, true, true);
		funcTypeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		new Label(this, SWT.NONE);
		
		Label label_2 = new Label(this, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label_2.setText("目录编码");
		
		funcSubPkgText = new Text(this, SWT.BORDER);
		funcSubPkgText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		new TextCheckPolicy(funcSubPkgText,TextCheckPolicy.POLICY_PACKAGE_NAME);
		toolkit.adapt(funcSubPkgText, true, true);
		new Label(this, SWT.NONE);

		final Label tablenameLabel = new Label(this, SWT.NONE);
		tablenameLabel.setText("主  表");

		tableNameCombo = new Combo(this, SWT.NONE);
		tableNameCombo.setForeground(ResourceUtil.getColor(255, 255, 255));
		tableNameCombo.setBackground(ResourceUtil.getColor(128, 0, 255));
		tableNameCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		tableNameCombo.setItems(this.getTables());
		new AutocompleteComboInput(tableNameCombo);
		new Label(this, SWT.NONE);

		final Label tablenameLabel_1 = new Label(this, SWT.NONE);
		tablenameLabel_1.setText("从  表");

		final TableViewer tableViewer = new TableViewer(this, SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER);
		table = tableViewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		toolkit.adapt(table, true, true);
		final GridData gd_table = new GridData(SWT.FILL, SWT.FILL, true, true);
		gd_table.heightHint = 110;
		table.setLayoutData(gd_table);

		final TableColumn tableNameColumn = new TableColumn(table, SWT.NONE);
		tableNameColumn.setWidth(150);
		tableNameColumn.setText("表 名");

		final TableColumn editModeColumn = new TableColumn(table, SWT.NONE);
		editModeColumn.setWidth(150);
		editModeColumn.setText("编辑模式");

		final TableColumn foreignKeyColumn = new TableColumn(table, SWT.NONE);
		foreignKeyColumn.setWidth(150);
		foreignKeyColumn.setText("外键字段");
		
		final TableColumn sortFieldColumn = new TableColumn(table, SWT.NONE);
		sortFieldColumn.setWidth(150);
		sortFieldColumn.setText("排序字段");
		
		
		tableViewer.setLabelProvider(new SubTableInfoProvider());
		tableViewer.setContentProvider(new ArrayContentProvider());
		subTableConfigEditors = new CellEditor[table.getColumnCount()]; 
		subTableConfigEditors[0] = new SubTableConfigProviderEditor(modelEditor,tableViewer,table);
		subTableConfigEditors[1] = new ComboBoxCellEditor(table,SubTableConfig.editModes, SWT.READ_ONLY);
		
		final Composite composite = new Composite(this, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
		final GridLayout gridLayout_1 = new GridLayout();
		gridLayout_1.verticalSpacing = 0;
		gridLayout_1.horizontalSpacing = 0;
		gridLayout_1.marginWidth = 0;
		gridLayout_1.marginHeight = 0;
		composite.setLayout(gridLayout_1);
		toolkit.adapt(composite);

		tableViewer.setCellEditors(subTableConfigEditors);
		tableViewer.setColumnProperties(SubTableConfig.columnProperties); 
		
		TableViewerKeyboardSupporter columnTableViewerSupporter = new TableViewerKeyboardSupporter(tableViewer); 
		columnTableViewerSupporter.startSupport();
		
		tableViewer.setCellModifier(new ICellModifier(){
			public boolean canModify(Object element, String property) {
				return true;
			}
			public Object getValue(Object element, String property) {
				SubTableConfig subTableConfig = (SubTableConfig) element; 
				if (SubTableConfig.TABLE_NAME.equals(property)){
					return subTableConfig.getTableName();
				}
				else if (SubTableConfig.EDIT_MODE.equals(property)){
					return getEditModelIndex(subTableConfig.getEditMode());
				}
				else if (SubTableConfig.FOREIGN_KEY.equals(property)){
					return subTableConfig.getForeignKey();
				}
				else if (SubTableConfig.SORT_FIELD_KEY.equals(property)){
					return subTableConfig.getSortField();
				}				
				return null;
			}
			private int getEditModelIndex(String editMode){
				int result = 0;
				for (int i=0;i < SubTableConfig.editModes.length;i++){
					if (SubTableConfig.editModes[i].equals(editMode)){
						result = i;
						break;
					}
				}
				return result;
			}
			public void modify(Object element, String property, Object value) {
				TableItem item = (TableItem)element;
				SubTableConfig subTableConfig = (SubTableConfig)item.getData();
				boolean changed = false;
				if (SubTableConfig.EDIT_MODE.equals(property)){
					Integer index = (Integer)value;
					if (index != -1 && !SubTableConfig.editModes[index].equals(subTableConfig.getEditMode())){
						subTableConfig.setEditMode(SubTableConfig.editModes[index]);
						changed = true;
					}
				}
				else if (SubTableConfig.FOREIGN_KEY.equals(property)){
					if (!String.valueOf(value).equals(subTableConfig.getForeignKey())){
						subTableConfig.setForeignKey(String.valueOf(value));
						changed = true;
					}
				}
				else if (SubTableConfig.SORT_FIELD_KEY.equals(property)){
					if (!String.valueOf(value).equals(subTableConfig.getSortField())){
						subTableConfig.setSortField(String.valueOf(value));
						changed = true;
					}
				}				
				if (changed){
					modelEditor.setModified(true);
					modelEditor.fireDirty();
					tableViewer.refresh();
				}
			}
		});
		tableViewer.setInput(this.funcModel.getSubTableConfigs());
		
		final Button addrowButton = new Button(composite, SWT.NONE);
		addrowButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				new AddOrDelOperation().addRow(tableViewer,SubTableConfig.class);
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		addrowButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		addrowButton.setText("添加");

		final Button deleteButton = new Button(composite, SWT.NONE);
		deleteButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				new AddOrDelOperation().delRow(tableViewer);
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		deleteButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		deleteButton.setText("删除");

		final Button upButton_1 = new Button(composite, SWT.NONE);
		upButton_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int selectedIndex = tableViewer.getTable().getSelectionIndex();
				new UpOrDownOperation().moveUp(tableViewer, selectedIndex);
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		upButton_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		upButton_1.setText("上移");

		final Button downButton_1 = new Button(composite, SWT.NONE);
		downButton_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int selectedIndex = tableViewer.getTable().getSelectionIndex();
				new UpOrDownOperation().moveDown(tableViewer, selectedIndex);
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		downButton_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		downButton_1.setText("下移");		
		

		final Composite formComposite = new Composite(this, SWT.NONE);
		formComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));
		final GridLayout gridLayout_4 = new GridLayout();
		gridLayout_4.marginHeight = 2;
		gridLayout_4.horizontalSpacing = 0;
		gridLayout_4.verticalSpacing = 0;
		gridLayout_4.marginWidth = 0;
		formComposite.setLayout(gridLayout_4);

		final TabFolder tabFolder = new TabFolder(formComposite, SWT.NONE);
		final GridData gd_tabFolder = new GridData(SWT.FILL, SWT.FILL, true, true);
		gd_tabFolder.heightHint = 254;
		tabFolder.setLayoutData(gd_tabFolder);
		toolkit.adapt(tabFolder, true, true);
		
		final TabItem tabItem_1 = new TabItem(tabFolder, SWT.NONE);
		tabItem_1.setText("列表SQL");

		listSqlText = new Text(tabFolder, SWT.MULTI | SWT.BORDER);
		toolkit.adapt(listSqlText, true, true);
		tabItem_1.setControl(listSqlText);

		final TabItem tabItem = new TabItem(tabFolder, SWT.NONE);
		tabItem.setText("扩展属性");
		sMExtendAttribute = new MSExtendAttribute(tabFolder,SWT.NONE);
		sMExtendAttribute.setModelEditor(modelEditor);
		tabItem.setControl(sMExtendAttribute);
	}
	public void dispose() {
		super.dispose();
	}
	protected void checkSubclass() {
	}
	public Combo getTableNameCombo() {
		return tableNameCombo;
	}

	public MasterSubFuncModel buildConfig(){
		String tableName = tableNameCombo.getText();
		if (!StringUtil.isNullOrEmpty(tableName)) {
			funcModel.setTableName(tableName);
		}
		funcModel.setFuncName(funcNameText.getText());
		funcModel.setFuncSubPkg(funcSubPkgText.getText());
		funcModel.setListSql(listSqlText.getText());
		funcModel.setServiceId(sMExtendAttribute.getServiceIdText().getText());
		funcModel.setImplClassName(sMExtendAttribute.getImplClassNameText().getText());
		funcModel.setInterfaceName(sMExtendAttribute.getInterfaceNameText().getText());
		funcModel.setListJspName(sMExtendAttribute.getListJspNameText().getText());
		funcModel.setDetailJspName(sMExtendAttribute.getDetailJspNameText().getText());

		funcModel.setExportCsv(sMExtendAttribute.getExportCsvBtn().getSelection());
		funcModel.setExportXls(sMExtendAttribute.getExportXslBtn().getSelection());
		funcModel.setPagination(sMExtendAttribute.getPaginationBtn().getSelection());
		funcModel.setSortAble(sMExtendAttribute.getSortListBtn().getSelection());
		funcModel.setTemplate(sMExtendAttribute.getTemplateCombo().getText());
		return this.funcModel;
	}

	public void initValues() {
		int tableCount = this.tableNameCombo.getItemCount();
		if (funcModel.getTableName() != null){
			for (int i=0;i < tableCount;i++){
				String tableName = this.tableNameCombo.getItem(i).toLowerCase();
				if (this.funcModel.getTableName().toLowerCase().equals(tableName)){
					this.tableNameCombo.select(i);
					break;
				}
			}
		}
		funcNameText.setText(this.funcModel.getFuncName());
		funcTypeText.setText(this.funcModel.getFuncTypeName());
		funcSubPkgText.setText(this.funcModel.getFuncSubPkg());
		listSqlText.setText(this.funcModel.getListSql().trim());
		sMExtendAttribute.getServiceIdText().setText(funcModel.getServiceId());
		sMExtendAttribute.getImplClassNameText().setText(funcModel.getImplClassName());
		sMExtendAttribute.getInterfaceNameText().setText(funcModel.getInterfaceName());
		sMExtendAttribute.getListJspNameText().setText(funcModel.getListJspName());
		sMExtendAttribute.getDetailJspNameText().setText(funcModel.getDetailJspName());
		String template = funcModel.getTemplate();
		if (StringUtil.isNullOrEmpty(template)){
			sMExtendAttribute.getTemplateCombo().select(0);
		}else{
			sMExtendAttribute.getTemplateCombo().setText(template);			
		}
		sMExtendAttribute.getExportCsvBtn().setSelection(funcModel.isExportCsv());
		sMExtendAttribute.getExportXslBtn().setSelection(funcModel.isExportXls());
		sMExtendAttribute.getPaginationBtn().setSelection(funcModel.isPagination());
		sMExtendAttribute.getSortListBtn().setSelection(funcModel.isSortAble());
		

	}
	public Text getListSqlText(){
		return listSqlText;
	}
	public Text getFuncSubPkgText(){
		return funcSubPkgText;
	}
	public MSExtendAttribute getsMExtendAttribute() {
		return sMExtendAttribute;
	}
	public void registryModifier() {
		funcNameText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		funcSubPkgText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!funcSubPkgText.getText().equals(funcModel.getFuncSubPkg())){
					modelEditor.setModified(true);
					modelEditor.fireDirty();				
				}
			}
		});
		sMExtendAttribute.getPaginationBtn().addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		sMExtendAttribute.getSortListBtn().addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		sMExtendAttribute.getExportCsvBtn().addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		sMExtendAttribute.getExportXslBtn().addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		sMExtendAttribute.getTemplateCombo().addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		sMExtendAttribute.getDetailJspNameText().addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		sMExtendAttribute.getListJspNameText().addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		sMExtendAttribute.getInterfaceNameText().addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		sMExtendAttribute.getImplClassNameText().addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		sMExtendAttribute.getServiceIdText().addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		tableNameCombo.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		listSqlText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
	}
}
class SubTableInfoProvider extends LabelProvider implements ITableLabelProvider {
	public String getColumnText(Object element, int columnIndex) {
		if (element instanceof SubTableConfig) {
			SubTableConfig subTableConfig = (SubTableConfig) element;
			if (columnIndex == 0) {
				return subTableConfig.getTableName();
			} else if (columnIndex == 1) {
				return subTableConfig.getEditMode();
			}
			else if (columnIndex == 2) {
				return subTableConfig.getForeignKey();
			}
			else if (columnIndex == 3) {
				return subTableConfig.getSortField();
			}
		}
		return null;
	}
	public Image getColumnImage(Object element, int columnIndex) {
		return null;
	}
}